<?php

require_once PHP_UI_PATH . DS . 'UIControl.php';
require_once PHP_UI_PATH . DS . 'DataSet.php';

class Select extends DataSetUIControl implements DataSet {

    function __construct() {
        $this->addStyleClass("select");
    }

    protected function getControlRendering() {
        $render = "<select name='{$this->getName()}' id='_{$this->getId()}' class='{$this->getStyleClasses()}'>";

        $valor = $this->getValue();
        $i = 0;
        $primeraOpcion = "";
        
        foreach ($this->getOptions() as $value => $opcion) {
            if ($i == 0) {
                $primeraOpcion = $opcion;
                $i++;
            }
            $seleccionado = "";
            
            if($valor == $opcion){
                $seleccionado =  "selected='selected'";
                $primeraOpcion = $valor;
            }
            
            $render .= "<option value='$value' $seleccionado >$opcion</option>";
        }
        $render .= "</select>";

        $render .= "<span id='hidden_{$this->getId()}' class='input text hidden' > ¿Cual? <input type='text' name='{$this->getName()}' value='$primeraOpcion'/></span>";

        return $render;
    }

    protected function getScriptRendering() {
        $script = "
            function check(){
                var id = this.id;
                var value = $('#' + id).val().toUpperCase();
                if(value == 'OTRO' || value == 'OTROS' || value == 'OTRA' || value == 'OTRAS'){
                    $('#hidden' + id).show();
                    $('#hidden' + id + ' input').val('');
                } else {
                    $('#hidden' + id).hide();
                    $('#hidden' + id + ' input').val(value);
                }

                return true;
            }

            $('.hidden').hide();
            $('.select').change(check);
            $('.select').click(check);
        ";
        return $script;
    }

}

?>
